/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
// 第一种,没有优化前的代码
class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null) return true;
        int l = depth(root.left);
        int r = depth(root.right);
        return Math.abs(l-r) <= 1 && isBalanced(root.left) && isBalanced(root.right);
    }

    public int depth(TreeNode root){
        if(root == null) return 0;
        return Math.max(depth(root.left),depth(root.right))+1;
    }

}


// 第二种,经过优化处理(将判断平衡二叉树的条件放入求深度的函数中)
class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null) return true;
        if(depth(root) == -1) return false;
        return true;
    }

    public int depth(TreeNode root){
        if(root == null) return 0;
        int left = depth(root.left);
        if(left == -1) return -1;
        int right = depth(root.right);
        if(right == -1) return -1;
        if(Math.abs(left - right) > 1) return -1;
        return Math.max(left,right) + 1;
    }

}